<?php

namespace Thrift;


use THBaseServiceClient;
use Thrift\Exception\TTransportException;
use Thrift\Protocol\TBinaryProtocol;
use Thrift\Transport\TBufferedTransport;
use Thrift\Transport\TSocket;

class HClient
{

	private TSocket|null $socket = null;


	private TBufferedTransport|null $bufferedTransport = null;


	private THBaseServiceClient|null $baseServiceClient = null;


	private string $host = '';

	private int $port = 0;


	private array $options;

	/**
	 * @param string $host
	 * @param int $port
	 * @param array $options
	 */
	public function __construct(string $host, int $port, array $options = [
		'send_timeout' => 10000,
		'recv_timeout' => 20000,
		'debug' => true
	])
	{
		$this->host = $host;
		$this->port = $port;

		$this->options = $options;

		$this->connect();
	}


	/**
	 *
	 */
	protected function connect(): void
	{
		$this->socket = new TSocket($this->host, $this->port);
		if (isset($this->options['send_timeout'])) {
			$this->socket->setSendTimeout($this->options['send_timeout']);
		}
		if (isset($this->options['recv_timeout'])) {
			$this->socket->setSendTimeout($this->options['recv_timeout']);
		}
		if (isset($this->options['debug'])) {
			$this->socket->setDebug($this->options['debug']);
		}
		$this->bufferedTransport = new TBufferedTransport($this->socket);
		$binaryProtocol = new TBinaryProtocol($this->bufferedTransport);
		$this->baseServiceClient = new THBaseServiceClient($binaryProtocol);
	}


	/**
	 * @return THBaseServiceClient
	 * @throws TTransportException
	 */
	public function getSocket(): THBaseServiceClient
	{
		if (!$this->bufferedTransport->isOpen()) {
			$this->bufferedTransport->open();
		}
		return $this->baseServiceClient;
	}


	/**
	 *
	 */
	public function close()
	{
		$this->bufferedTransport->close();
	}


}
